/*
 * maz_mod_led.c
 *
 *  Created on: Jun 7, 2020
 *      Author: Paul
 */

#include "maz_mod_led.h"

/**
 * "dlvl" variables must be defined if debug message is to be printed through the dlog/dmsg, and "dlvl" must be declared static
 */
//static int dlvl = DINF;

int MAZ_Mod_led_init(MAZMOD_LED_CTRL *pctrl)
{
    GPIO_TypeDef *port = NULL;
    uint32_t pin = 0;
    MAZMOD_E_LED_POLAR polar = 0;
    MAZMOD_E_LED_STATUS status = 0;
    GPIO_InitTypeDef GPIO_InitStruct = { 0 };

    port = (GPIO_TypeDef *)pctrl->cfg.gpio.cfg.port;
    pin = pctrl->cfg.gpio.cfg.pin;
    polar = pctrl->cfg.polar;
    status = pctrl->cfg.status;

    /* GPIO Ports Clock Enable */
    MAZ_Drv_gpio_clk_enable(port);

    /* GPIO Pin Configure */
    GPIO_InitStruct.Pin  = pin;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
    GPIO_InitStruct.Pull = (MAZMOD_E_LED_POLAR_HIGH == polar) ? GPIO_PULLDOWN : GPIO_PULLUP;
    HAL_GPIO_Init(port, &GPIO_InitStruct);

    /* Default Status Configure */
    MAZ_Mod_led_status_set(pctrl, status);

    return MAZRET_OK;
}

int MAZ_Mod_led_status_set(MAZMOD_LED_CTRL *pctrl, MAZMOD_E_LED_STATUS status)
{
    uint32_t pin = 0;
    GPIO_TypeDef *port = NULL;
    MAZMOD_E_LED_POLAR polar = 0;

    port = (GPIO_TypeDef *)pctrl->cfg.gpio.cfg.port;
    pin = pctrl->cfg.gpio.cfg.pin;
    polar = pctrl->cfg.polar;

    switch (status)
    {
    case MAZMOD_E_LED_STATUS_ON:
        HAL_GPIO_WritePin(port, pin, polar);
        break;
    case MAZMOD_E_LED_STATUS_OFF:
        if (MAZMOD_E_LED_POLAR_HIGH == polar)
            polar = MAZMOD_E_LED_POLAR_LOW;
        else if (MAZMOD_E_LED_POLAR_LOW == polar)
            polar = MAZMOD_E_LED_POLAR_HIGH;
        HAL_GPIO_WritePin(port, pin, polar);
        break;
    case MAZMOD_E_LED_STATUS_TOGGLE:
        HAL_GPIO_TogglePin(port, pin);
        break;
    }

    return 0;
}
